package com.marvels.approve.common.utils;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.druid.util.StringUtils;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.common.utils.ServerProperties;

/**
 * 获取担保费率
 */
@Component
public class InsuranceRateUtil {
	
	
	private static String filePath;

	@Value("${config.properties.path}")
	public void setFilePath(String filePath){
		InsuranceRateUtil.filePath = filePath;
	}
	/**
	 * 获取保单费率
	 * @param productType
	 * @return
	 */
	public static String getBxAssureRate(String productType){
		String rate = null;
		String qaBdRateMap = ServerProperties.getValue(filePath, "resource.properties", "QA_BD_RATE");
		if(!StringUtils.isEmpty(qaBdRateMap)){
			String[] rateArray =  qaBdRateMap.split(",");
			if(rateArray!=null && rateArray.length>0){
				for (String rateObj : rateArray) {
					if(!StringUtils.isEmpty(rateObj)){
						String[] rateInfo = rateObj.split("-");
						if(rateInfo!=null && rateInfo.length>0){
							if(rateInfo[0].equals(productType)){
								rate = rateInfo[2];
							}
						}
					}
				}
			}
		}
		return rate;
	}
	/**
	 * 获取保单金额
	 * @param loan
	 * @return
	 * @throws Exception 
	 */
	public static BigDecimal getBxMoney(McamLoanApplyInfoDTO loan) throws Exception{
		BigDecimal loanMoney = loan.getPrincipalAmtAct();
		String insuranceRate = InsuranceRateUtil.getBxAssureRate(loan.getProductType());
		if(StringUtils.isEmpty(insuranceRate)){
			throw new Exception("保费费率没有配置！");
		}
		BigDecimal bxMoney = loanMoney.multiply(new BigDecimal(insuranceRate).divide(new BigDecimal(100))).setScale(0, BigDecimal.ROUND_HALF_UP);
		/**
		 * 规则：总保费除以总期数的值必须是10的倍数,如果不是，则需要取总保费向上浮动最小并满足条件的值
		 */
		int amount =(int)Math.ceil(bxMoney.doubleValue());//保费金额向上取整
		amount = (amount%(loan.getApplyTerms()*10)) == 0 ? amount : (loan.getApplyTerms()*10 - amount%(loan.getApplyTerms()*10) + amount);
		return new BigDecimal(amount);
	}
}
